define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shops/middleman/index' + location.search,
                    add_url: 'shops/middleman/add',
                    edit_url: 'shops/middleman/edit',
                    // del_url: 'shops/middleman/del',
                    multi_url: 'shops/middleman/multi',
                    import_url: 'shops/middleman/import',
                    table: 'user',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search:false,
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),'visible':false,'operate':false},
                        {field: 'no', title: 'ID'},
                        // {field: 'pid', title: '上级邀请人'},
                        {
                            field: 'avatar',
                            title: '经纪人头像', operate: false,
                            events: Table.api.events.image,
                            formatter: Table.api.formatter.image
                        },
                        {field: 'nickname', title: '经纪人昵称', operate: 'LIKE'},
                        {field: 'mobile', title: '联系电话', operate: 'LIKE'},
                        {field: 'money', title: '余额', operate: false},
                        {field: 'bill', title: '待支付账单', operate: false},
                        {field: 'freeze_money', title: '冻结余额', operate: false},
                        {field: 'real_name', title: '真实姓名', operate: 'LIKE'},
                        {field: 'card_no', title: '银行卡号', operate: 'LIKE'},
                        {field: 'bank_name', title: '开户行', operate: 'LIKE'},
                        {field: 'ledger_no', title: '易宝商户号',},
                        {field: 'rebate_amt', title: '返点金额', operate: false, sortable: true},
                        {field: 'anickname', title: '所属销售', operate: 'LIKE'},
                        {
                            field: 'logintime',
                            title: '登录时间',
                            operate: false,
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {"hidden": '封禁', "normal": '正常'},
                            formatter: Table.api.formatter.status
                        },
                        // {field: 'verification', title: __('Verification'), operate: 'LIKE'},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [{
                                    name: "item",
                                    classname: "btn btn-xs btn-info btn-dialog",
                                    icon: "fa",
                                    text: "关联账单",
                                    url: "shops/middleman/item",
                                },
                                {
                                    name: 'detail',
                                    text: __('资金管理'),
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa',
                                    url: 'shops/middleman/wallet',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    }
                                },
                                {
                                    name: 'edit',
                                    text: '编辑',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-success btn-editone',
                                    url: 'shops/middleman/detail'
                                },
                                {
                                    name: "lh",
                                    title: "拉黑",
                                    classname: "btn btn-xs btn-danger btn-dialog",
                                    icon: "fa",
                                    text: "拉黑",
                                    url: "shops/middleman/lh",
                                    extend: 'data-area=["500px","270px"]',
                                    visible: function(row){
                                        if ("normal" == row.status) return ! 0
                                    }, 
                                    refresh: true
                                },
                                {
                                    name: "hfjy",
                                    title: "恢复",
                                    classname: "btn btn-xs btn-info btn-magic btn-ajax",
                                    icon: "fa",
                                    text: "恢复",
                                    confirm: "确认恢复？",
                                    url: "shops/middleman/hfjy",
                                    visible: function(row){
                                        if ("hidden" == row.status) return ! 0
                                    }, 
                                    refresh: true
                                },
                                {
                                    name: 'transfer',
                                    text: '线下转账',
                                    // dropdown: "更多",
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-warning btn-dialog',
                                    url: 'shops/middleman/transfer',
                                    visible: function(row){
                                        if (Config.middleman.middleman_id == row.id) return ! 0
                                    }, 
                                    refresh: true
                                },
                                {
                                    name: 'transferlog',
                                    text: '线下转账记录',
                                    icon: 'fa',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'shops/middleman/transferlog',
                                    visible: function(row){
                                        if (Config.middleman.middleman_id == row.id) return ! 0
                                    }, 
                                    refresh: true
                                },
                            ]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        wallet: function () {
            let ids = $("input[name=user_id]").val();
            $(document).on('click', '.btn-callback', function () {
                // console.log('wallet', $("input[name=wallet]").val(),$(this).data('field'));
                let field = $(this).data('field');
                let val = $("input[name=" + field + "]").val();
                Fast.api.ajax({
                    url: "shops/middleman/wallet/ids/" + ids,
                    data: {field: field, val: val},
                    success: function (data, ret) {
                        console.log('ajax', data, ret)
                        // Layer.close(index);
                        if (data.code == 1) {
                            $("input[name=" + field + "]").val(0);
                            $("." + field).text(data.data);
                            Layer.closeAll();
                            Layer.alert(data.msg);
                            return false;
                        } else {
                            Layer.closeAll();
                            Layer.alert(data.msg, {title: __('Warning'), icon: 1});
                            return false;
                        }
                    }
                });
                // Fast.api.close($("input[name=callback]").val());
            })
        },
        item: function () {
            var ids = $("#assign-data-ids").val();
            var shop_name = $("#shop_name").val();
            var date = $("#date").val();
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                },
                exportTypes: ['excel'],
                exportOptions: {
                    fileName: shop_name + ' ' + date,
                    ignoreColumn: [0, 'operate'],
                    onBeforeSaveToFile: function (data, fileName, type, charset, encoding, bom) {
                        return $.fn.bootstrapTable.defaults.extend.savestatus;
                    },
                    onCellHtmlHyperlink: function ($cell, rowIndex, colIndex, href, htmlData) {
                        var html = $.parseHTML(htmlData);
                        var inputidx = 0;
                        var selectidx = 0;
                        var result = '';

                        $.each(html, function () {
                            if ($(this).is("input")) {
                                result += $cell.find('input').eq(inputidx++).val();
                            } else if ($(this).is("select")) {
                                result += $cell.find('select option:selected').eq(selectidx++).text();
                            } else if ($(this).is("img")) {
                                var src = $(this).attr('src');
                                if (src != 'https://oss.chbcplus.com/assets/img/blank.gif') {
                                    result += '<a href="'+src+'">'+src+'</a>';
                                }
                                // if (src.indexOf('http') === -1) {
                                //     $(this).attr('src', window.location.origin + src);
                                // }
                                // $(this).attr("width", "40").attr("height", "40").attr('class', '');
                                // result += '<div>' + $(this).get(0).outerHTML + '</div>';
                            } else {
                                if (typeof $(this).html() === 'undefined') {
                                    result += $(this).text();
                                } else if (jQuery().bootstrapTable === undefined ||
                                    ($(this).hasClass('filterControl') !== true &&
                                        $cell.parents('.detail-view').length === 0)) {
                                    result += $(this).html();
                                }
                            }
                        });
                        return result;
                    }
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shops/middleman/item/ids/' + ids,
                pk: 'id',
                sortName: 'id',
                search:false,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'play_order_no', title: '订单编号', operate: false},
                        // {field: 'user.nickname', title: '下单用户', operate: false},
                        // {field: 'shop.shop_name', title: '店铺名称', operate: false},
                        // {field: 'shop.shop_type_text', title: '下单平台', operate: false},
                        {field: 'user_id', title: '下单用户', operate: false},
                        {field: 'shop_no', title: '店铺名称', operate: false},
                        {field: 'platform_no', title: '下单平台', operate: false},
                        {field: 'wm_order_sn', title: '外卖单号', operate: false},
                        {field: 'back_money_text2', title: '优惠条件', operate: false},
                        {field: 'actual_pay', title: '实付金额', operate: false},
                        {field: 'rebate_amt', title: '商家需支付金额', operate: false},
                        // {field: 'service_amt', title: '服务费'},
                        {field: 'scheme_no_text', title: '活动方案', operate: false},
                        {field: 'place_time', title: '抢单时间', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'order_status', title: __('Status'), operate: false, searchList: {"1":"待上传","2":"待审核","3":"已完成","6":"待商家复审","-1":"已取消","-2":"超时取消","-3":"已拒绝",'-5':'不满意反馈','-6':'不满意通过','-7':'异常订单','-8':'异常订单（客服已处理）','-9':'异常订单（已完成）','-4':'异常订单（已取消）'}, formatter: Table.api.formatter.status},
                        {field: 'is_pay', title: '是否结算', searchList: {"0":"未结算","1":"已结算"}, formatter: Table.api.formatter.status},
                        {field: 'one_image', title: '订单截图1', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'two_image', title: '订单截图2', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'three_image', title: '订单截图3', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'create_dt', title: __('Createtime'), operate:'RANGE', operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'update_dt', title: __('Updatetime'), operate:'RANGE', operate: false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        transferlog: function () {
            var ids = $("#assign-data-ids").val();
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                },
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shops/middleman/transferlog/ids/' + ids,
                pk: 'id',
                sortName: 'id',
                search:false,
                searchFormVisible:true,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'start_date_text', title: '活动时间', operate: false},
                        {field: 'yunzhan_order_no', title: '订单号', operate: false},
                        {field: 'sum', title: '应付金额', operate: false},
                        {field: 'img', title: '转账凭证', operate: false,events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'submit_by', title: '操作用户', operate: false},
                        {field: 'update_dt', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        transfer: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
